import Vue from "vue";
import Vuex, { StoreOptions } from "vuex";

Vue.use(Vuex);

const fetchData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(["web", "java", "python", "c++", "react"]);
    }, 1000);
  });
};

const moduleA: StoreOptions<any> = {
  state: () => {
    return {
      some: "zhangsan"
    };
  },
  // mutations 执行commit操作
  mutations: {
    changeName(state, name) {
      state.name = name;
    }
  }
  // // actions 执行dispatch操作
  // actions: {
  //   add(context, payload) {
  //     console.log("payload", payload);
  //
  //     fetchData().then((data) => {
  //       context.commit("add", data);
  //     });
  //   }
  // },
  // getters: {
  //   count: (state, getters, rootState, rootGetters) => state.name
  // }
};

export const store = new Vuex.Store<{
  count: number;
  list: string[];
}>({
  state: {
    count: 0,
    list: []
  },
  modules: {
    a: moduleA
  },
  // mutations 执行commit操作
  mutations: {
    increment(state, count) {
      state.count = state.count + parseFloat(count ?? 0);
    },
    add(state, list) {
      state.list = list;
    }
  },
  // actions 执行dispatch操作
  actions: {
    add(context, payload) {
      fetchData().then((data) => {
        context.commit("add", data);
      });
    }
  },
  getters: {
    count: (state, getters, rootState, rootGetters) => state.count,
    doneTodos: (state) => {
      return state.list.filter((item = "") => {
        return item.length >= 4;
      });
    }
  }
});
